package com.example.yoga.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yoga.entity.User;
import com.example.yoga.service.IUserService;
import com.example.yoga.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class LoginController {


    @Autowired
    private IUserService userService;

    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/login")
    public JsonResult<User> login(HttpSession session, @RequestBody User user){
        System.out.println(user.toString()+"*******************");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("userName",user.getUsername());
        User user1 = userService.getOne(wrapper);
        System.out.println(user1);
        if (user1!=null&& user1.getUserpassword().equals(user.getUserpassword())){
            //以用户名为键，然后保存用户信息
            session.setAttribute(user.getUsername(),user1);
//            System.err.println(session.getAttribute("卡卡"));
            return new JsonResult<>(2000,user1);
        }
        return new JsonResult<>(4000,"登陆失败");
    }


    /**
     * 用户退出
     */
    @RequestMapping(value = "/exit",method = RequestMethod.GET)
    public JsonResult<Void> exit(HttpSession session,String username){
        /**
         * 清除缓存
         */
        try{
            session.removeAttribute(username);
            return new JsonResult<>(2000,"退出成功！");
        }catch (Exception e){
            return new JsonResult<>(4000,"退出异常，系统出错！");
        }
    }
}
